<template>
  <div>
    <div class="operation-group">
      <el-button plain type="single-number" @click="chooseContract">
        删除行
      </el-button>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <ux-grid
        ref="plxTable"
        keep-source
        width="100%"
        widthResize
        show-overflow="title"
        show-summary
        :summary-method="getSummaries"
        @select-all="handleCheckChange"
        @select="handleCheckChange"
        :header-cell-class-name="must"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        :checkboxConfig="{ checkMethod: handleSelectable, highlight: true }"
      >
        <ux-table-column
          type="checkbox"
          min-width="55"
          fixed="left"
          show-overflow="none"
        />
        <ux-table-column
          title="序号"
          type="index"
          min-width="50"
          fixed="left"
          :resizable="true"
        />

        <ux-table-column
          :show-overflow-tooltip="true"
          field="storageListCode"
          title="批次号"
          min-width="260"
          fixed="left"
          :resizable="true"
        >
          <template v-slot="scope">
            <el-input v-model="scope.row.storageListCode" disabled></el-input>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="materialCode"
          title="设备物资编码"
          min-width="150"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.materialCode }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="materialName"
          title="设备物资名称"
          min-width="300"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.materialName }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="materialState"
          title="设备物资说明"
          min-width="130"
          :resizable="true"
        >
          <template v-slot="scope">
            <span>{{ scope.row.materialState }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="measureUnit"
          title="计量单位"
          min-width="90"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.measureUnit }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="unitPriceWithTax"
          title="含税单价"
          min-width="140"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span
              v-if="scope.row.isOtherCost != 1 && scope.row.isServices != 1"
              >{{ scope.row.unitPriceWithTax | filterTax }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="moneyWithTax"
          title="含税金额"
          min-width="140"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.moneyWithTax | filterTax }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="unStorageCount"
          title="剩余可入库数量"
          min-width="140"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span
              v-if="scope.row.isOtherCost != 1 && scope.row.isServices != 1"
              >{{ scope.row.unStorageCount }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="storageCount"
          title="入库数量"
          min-width="140"
          :edit-render="{ autofocus: '.el-input__inner' }"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <el-input
              v-if="scope.row.isOtherCost != 1 && scope.row.isServices != 1"
              v-model="scope.row.storageCount"
              @keyup.native="scope.row.storageCount = oninput(scope.row)"
              :max="scope.row.settlementCount"
              @blur="getblur($event, scope.row, 'blur', 'storageCount')"
            ></el-input>
          </template>
          <template v-slot="scope">
            <span
              class="my-input-sc"
              v-if="scope.row.isOtherCost != 1 && scope.row.isServices != 1"
              >{{ scope.row.storageCount }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="moneyWithoutTax"
          title="不含税金额"
          min-width="140"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.moneyWithoutTax | filterTax }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          title="关联入库单"
          min-width="200"
          show-overflow="none"
          :resizable="true"
        >
          <template v-slot:default="{ row }">
            <div class="relationBox">
              <purchaseList
                v-if="row.isOtherCost == 1 || row.isServices == 1"
                :isShow="true"
                btnText="选择"
                dialogTitle="选择"
                :searchInputArr="jsList.planSearchInputArr"
                :tableHeadOptions="jsList.planTableHeadOptions"
                :getTableList="listFinStorageRelatePage"
                :optionalParams="optionalParams"
                :selectTableList="
                  row.relationList.length > 0 ? row.relationList : relationList
                "
                :rowIndex="row.id"
                :storageFormTolal="storageForm.storageFormTolal"
                @confirm="planConfirm"
              />
              <!-- :selectTableList="row.relationList || relationList" -->
              <span class="relationRight" :title="row.relationCode">{{
                row.relationCode
              }}</span>
            </div>
          </template>
        </ux-table-column>
      </ux-grid>
    </div>
  </div>
</template>

<script>
import purchaseList from "../../components/dialogMultiSelectTableTow";
import jsList from "@/app/inventoryManagement/js";
import { listFinStorageRelatePage } from "../../api/add-item";
import { formatNumber } from "@/basa/utils";
import BigNumber from "bignumber.js";

export default {
  name: "contractList",
  props: {
    storageList: Array,
    storageForm: Object
  },
  components: { purchaseList },
  created() {},
  data() {
    return {
      jsList,
      form: {},
      rules: {},
      tableList: [], //子组件传来的参数
      // 选择合同弹窗组件
      formSearch: {
        pcConcId: "",
        materialsCode: "",
        materialsName: ""
      },
      dialogTableVisibleTextarea: false,
      dialogTableVisible: false, //控制弹窗显示隐藏
      tableDataDialogLeft: [],
      tableDataDialogRight: [],
      tempArr: [],
      lineClampBody: true,
      concChangesDel: [], //主合同变更删除清单
      checkedList: [],
      relationList: [
        {
          id: "00",
          flagCurrent: 1,
          storageCode: "当期"
        }
      ],
      code: 0,
      count: 0,
      optionalParams: {
        checkUsable: true,
        storageStatus: 5
      }
    };
  },
  watch: {
    storageList(newVal) {
      this.$nextTick(() => {
        this.$refs.plxTable.reloadData(newVal);
      });
    }
  },
  filters: {
    filterTax(value) {
      return Number(value).toFixed(2);
    }
  },
  methods: {
    must(obj) {
      //给表头加必选标识
      if (obj.column.title == "入库数量") {
        return "must";
      }
    },
    // 关联入库单确定按钮
    planConfirm(data, rowIndex) {
      if (data != []) {
        data.forEach(item => {
          item.storageId = item.id;
        });
      }
      let newArr = JSON.parse(JSON.stringify(data));
      this.storageList.forEach(item => {
        if (item.id === rowIndex) {
          item.relationList = newArr;
        }
      });
      this.storageList.forEach((item, index) => {
        if (item.isOtherCost == 1 || item.isServices == 1) {
          if (item.relationList && item.relationList.length > 0) {
            let newList = [];
            item.relationList.forEach(val => {
              // val.pkPurmatdetl = val.id;
              newList.push(val.storageCode);
            });
            item.relationCode = newList.join(",");
          } else {
            item.relationCode = item.storageCode;
          }
        }
      });
      this.relationList = [
        {
          id: "00",
          storageCode: "当期"
        }
      ];
    },
    oninput(row) {
      //      debugger
      //正则替换
      //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
      var str = row.storageCount.toString();
      str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
      str = str.replace(/^\./g, ""); // 必须保证第一个为数字而不是.
      str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      // 限制几位小数
      const arr = str.split(".");
      if (arr[arr.length - 1].length > 3 && arr.length == 2) {
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 1 && str.length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 2 && arr[0].length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = arr[0].substr(0, arr[0].length - 1);
      }
      return str;
    },
    getblur(e, row, eventType, nameModel) {
      if (row.storageCount != "") {
        let reg = /^\d*\.?\d*$/;
        if (reg.test(row.storageCount)) {
          const arr = row.storageCount.split(".");
          if (arr.length == 1 && row.storageCount.length > 12) {
            this.$message.warning("整数最多可以输入12位");
            row.storageCount = row.storageCount.substr(0, 12);
          }
        }

        row.moneyWithTax = new BigNumber(Number(row.unitPriceWithTax)).times(
          Number(row.storageCount)
        );
        row.moneyWithTax = (+row.moneyWithTax).toFixed(2);
        let taxRate = new BigNumber(Number(row.taxRate)).plus(1).toString();
        row.moneyWithoutTax = new BigNumber(Number(row.moneyWithTax)).dividedBy(
          taxRate
        );
        row.moneyWithoutTax = (+row.moneyWithoutTax).toFixed(2);
        row.storageCount = formatNumber(+row.storageCount, 3);
        if (eventType == "blur") {
          if (Number(row.storageCount) < row.settlementCount) {
            if (Number(row.storageCount) <= 0) {
              e.target.style.border = "1px solid red";
              this.$message({
                message: "入库数量不能为0",
                type: "error",
                showClose: true,
                ccuiCustom: true
              });
              row.storageCount = row.unStorageCount;
              row.moneyWithTax = new BigNumber(
                Number(row.unitPriceWithTax)
              ).times(Number(row.storageCount));
              row.moneyWithTax = (+row.moneyWithTax).toFixed(2);
              let taxRate = new BigNumber(Number(row.taxRate))
                .plus(1)
                .toString();
              row.moneyWithoutTax = new BigNumber(
                Number(row.moneyWithTax)
              ).dividedBy(taxRate);
              row.moneyWithoutTax = (+row.moneyWithoutTax).toFixed(2);
              return;
            } else {
              e.target.style.border = "1px solid red";
              if (Number(row.storageCount) > row.settlementCount) {
                this.$message({
                  message: "入库数量不能大于结算数量",
                  type: "error",
                  showClose: true,
                  ccuiCustom: true
                });
                row.storageCount = row.unStorageCount;
                row.moneyWithTax = new BigNumber(
                  Number(row.unitPriceWithTax)
                ).times(Number(row.storageCount));
                row.moneyWithTax = (+row.moneyWithTax).toFixed(2);
                let taxRate = new BigNumber(Number(row.taxRate))
                  .plus(1)
                  .toString();
                row.moneyWithoutTax = new BigNumber(
                  Number(row.moneyWithTax)
                ).dividedBy(taxRate);
                row.moneyWithoutTax = (+row.moneyWithoutTax).toFixed(2);
                return;
              }
              return row.storageCount;
            }
          }
        }
      } else {
        e.target.style.border = "1px solid red";
        this.$message({
          message: "入库数量不能为空",
          type: "error",
          showClose: true,
          ccuiCustom: true
        });
      }
    },
    handleSelectable({ row }) {
      if (row.isOtherCost == 1 || row.isServices == 1) {
        return false;
      } else {
        return true;
      }
    },
    // 删除行
    chooseContract() {
      if (this.tempArr.length < 1) {
        this.$message.warning("请选择一项");
        return;
      }
      let newArr = [];
      this.storageList.forEach(item => {
        if (item.isOtherCost != 1 && item.isServices != 1) {
          newArr.push(item);
        }
      });
      if (this.tempArr.length >= newArr.length) {
        this.$message.warning("清单至少保留一条");
        return;
      }
      const filterArr = this.storageList.filter(
        item => !this.tempArr.includes(item.id)
      );
      this.$emit("delectList", filterArr);
    },
    formSearchHandler() {},
    formSearchChange() {},
    // 列表单选 多选
    handleCheckAllChange(val) {
      if (val.length > 0) {
        val.forEach(item => {
          item.check = true;
        });
      }
    },
    handleCheckChange(val) {
      this.tempArr = val.map(item => item.id);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          // sums[index] = "合计";
          sums.push("合计");
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (
                column.title == "入库数量" ||
                column.title == "剩余可入库数量" ||
                column.title == "含税金额" ||
                column.title == "不含税金额"
              ) {
                return prev + curr;
              }
            } else {
              return prev;
            }
          }, 0);
          if (column.title == "入库数量") {
            sums[index] = sums[index] ? sums[index].toFixed(3) : "";
          }
          if (column.title == "剩余可入库数量") {
            sums[index] = sums[index] ? sums[index].toFixed(3) : "";
          }
          if (column.title == "含税金额") {
            sums[index] = sums[index].toFixed(2);
          }
          if (column.title == "不含税金额") {
            sums[index] = sums[index].toFixed(2);
          }
        } else {
          sums[index] = "";
        }

        this.storageForm.settlementCount = (+sums[10]).toFixed(3);
        this.storageForm.moneyWithTax = sums[8];
      });
      return [sums];
    },
    listFinStorageRelatePage
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table th.must > .cell:before {
  content: "*";
  color: #ff1818;
  margin-right: 5px;
}

.relationBox {
  display: flex;
  justify-content: center;
  align-items: center;
}

.relationBox .relationRight {
  display: inline-block;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 5px;
}

.operation-group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

/deep/ .ccui-form .ccui-form-child-table.el-table .el-input .el-input__inner {
  border: 1px solid #ccc;
}

/deep/ .ccui-multifunctional-table-wrapper {
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }

  .ccui-table-footer {
    padding-top: 0 !important;
  }
}

/deep/ .el-table__footer-wrapper {
  margin-top: 0px;
}

/deep/ .el-button.el-button--primary-font-mini {
  padding: 0 15px !important;
}

// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}

/deep/ .el-table__fixed,
/deep/ .el-table__fixed-right {
  pointer-events: none;

  td {
    pointer-events: auto;
  }
}

/deep/ .elx-table.is--empty .elx-table--empty-placeholder {
  top: 40px !important;
  height: 40px !important;
}

/deep/ .elx-table .elx-body--column.col--ellipsis,
.elx-table.elx-editable .elx-body--column {
  font-size: 13px;
}

.my-input-sc {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  -webkit-appearance: none;
  background-color: #ffffff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  font-size: inherit;
  outline: none;
  padding: 0 8px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
</style>
